const {
  $Toast
} = require('../../utils/iview/base/index');
const Tools = require('../../utils/modules/Tools');
import NetWork from '../../utils/modules/NetWork';


    //一、数据裁剪，把数据裁剪成数据（这里【1】是为了获取数组下标为1的数据）
    // var scene = decodeURIComponent(o.scene)
    // scene = scene.split('=')[1];


    // 这里区分一下两个id
    // 判断id是那个扫出来的
    // 这是其他设备扫的

    //  注：然后在分别两个设备ID中设置缓存是因为，如果我去选择其他车辆回来经度就会为空（传设备id就是为了传经纬度）
    // 然后在onshown那里写个获取缓存（在onshow写是为了每次都执行，不然点击回来经度也为空了）
const app = getApp();

var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({
  data: {
    type: 3,
    banner: null,
    student: null,
    yzmConfig: {
     
      url: 'api/v1/member_order_msn',
      method: 'POST',
      data: {

        phone: '',
        member_id: '',
      }

    },
    dail: '',
    // 默认不显示，刚进去的时候
    display:false,
    shopList: null,
    auth: true,
    //门店展示的数据
    shopname: [],
    index: 0,
    indexs: 0,
    vehicle: [],
    timal_msg: '',
    isloade: {
      hidden: false
    },
    id: '',
    _baseUrl: app.globalData._baseUrl,
    deviceList:'',
    indext:0
  },


  onLoad(o) {


    if (o.scene) {
      var scene = decodeURIComponent(o.scene)
      scene = scene.split('=')[1];
      wx.setStorageSync("scene", scene)
    }
    // 这个是从个人中心扫传过来的id
    else if (o.id) {
      var scene = o.id;
      wx.setStorageSync("scene", scene)
    }

    var _that = this
    _that.setTitle('信息确认');
    _that.setData({
      id: wx.getStorageSync('id'),
      store_name: wx.getStorageSync('store_name')
    })
    //如果有进行扫描则调用设备ID和调取获取信息saom的接口
    if (scene) {
      _that.setData({
        device_id: scene,
      })
      _that.saom()
    }
    // 验证码
    var user = wx.getStorageSync('user');
    _that.setData({
      user: user,
      "yzmConfig.data.member_id": user.id,
      "yzmConfig.data.phone": user.phone,
    })
    _that.storeDevice();

  },
  setms(e) {
    var value = e.detail.value;
    this.setData({
      dail: value
    })
  },
  onShow: function() {
    let _that = this;
    var usreAdd = wx.getStorageSync('usreAdd');
    _that.vehicleList();
    _that.isUserInfo();
    _that.setData({
      usreAdd: usreAdd,
      address: usreAdd.address
    })

    // _that.setData({
    //   user: user,
    //   "yzmConfig.data.phone": user.phone,
    //   "yzmConfig.data.member_id": user.id,
    //   usreAdd: usreAdd,
    //   address: usreAdd.address
    // })

    _that.setData({
      isclick: 0
    })
    //设备id的缓存在这里，如果读取缓存就取id
    if (wx.getStorageSync("scene")) {
      var scene = wx.getStorageSync("scene");
    }
    //相对应的这边也要调取扫描下单接口
    if (scene){
      _that.setData({
        device_id: scene,
      })
      _that.saom()
    }
  },
  bindCabinet(e){
    this.setData({
      indext:e.detail.value
    })
  },
  phonee(e) {
    this.setData({
      // 修改手机号码的时候显示
      display:true,
      "yzmConfig.data.phone": e.detail.value
    })
  },
  // 获取设备
  storeDevice() {
    let _that = this;
    var token = wx.getStorageSync('token');
    if (!token) {
      return;
    }
    let net = new NetWork(_that.data._baseUrl);
    net._request({
      url: 'api/v1/order/store_device',
      data: {
        //需要获取店铺id，所以要去获取，因为我们要去获取上一页的店铺id所以要去onLoad里面获取
        token: token,
        store_id: _that.data.id,
      },
      method: 'POST'
    }, '', res => {
      console.log(res,'data');
      let data = res.data.data;
      let obj = {o:{},a:[]};
      for(var i = 0; i<data.length; i++){
        let name = data[i].device_name;
        let id = data[i].id;
        obj.a.push(name);
        obj.o[i] = {id:id,name:name};
      }
      _that.setData({
        deviceList: obj
      })
    }, res => {
      if (res.data.error_code == 400 && res.data.msg == 'token无效或已过期') {
        app.refreshtoken(token);
        setTimeout(() => {
          _that.addpage();
        }, 1500)
      } else if (res.data.error_code == 400) {
        _that.setData({
          timal_msg: res.data.msg
        })
      }
    });
  },



  //one、调取默认车辆的接口（cid？）
  vehicleList() {
    //获取车辆列
    var _that = this;
    var token = wx.getStorageSync('token')
    if (!token) {
      return;
    }
    var net = new NetWork(_that.data._baseUrl);
    net._request({
      url: 'api/v1/member/mycar',
      data: {
        token: token
      },
      method: 'POST',
    }, '', res => {
      if (res.data.error_code == 0) {
        var min = res.data.data.data
        _that.setData({
          vehicle: min
        })
        // 车辆id是在这个里面取出的
        var vehicles = wx.getStorageSync('vehicles');
     
        for (var i = 0; i < min.length; i++) {
          if (vehicles && vehicles.id == min[i].id) {
            _that.setData({
              indexs: i,
              cid: min[i].id
            })
            break;
          }
          // 在个人中心那里显示设置默认的车辆
          else if (!vehicles && min[i].is_default) {
            _that.setData({
              // 这里加了个indexs: i,
              indexs: i,
              cid: min[i].id
            })
            break;
          } else if ((i + 1) == min.length && !min[i].is_default) {
            _that.setData({
              // 这里加了个indexs: i,
              indexs: 0,
              cid: min[0].id
            })
            break;
          }

        }
        _that.addpage();

      }
    }, res => {
      if (res.data.error_code == 400 && res.data.msg == 'token无效或已过期') {
        //token过期 重新执行该函数
        app.refreshtoken(token);
        setTimeout(() => {
          _that.vehicleList();
        }, 1500)

      }
    })
  },

  yzmsuccess (e){

  },

  yzmfail (e){
    this.setData({
      // 验证发送失败（已经验证过的）不显示
      display : false,
    })
  },

  //two、根据门店id和车辆id决定费用
  addpage() {
    let _that = this;
    var token = wx.getStorageSync('token');
    if (!token) {
      return;
    }

    let net = new NetWork(_that.data._baseUrl)
    net._request({
      url: 'api/v1/menu/menuInfo',
      data: {
        //需要获取店铺id，所以要去获取，因为我们要去获取上一页的店铺id所以要去onLoad里面获取
        token: token,
        car_id: _that.data.cid,
        store_id: _that.data.id,
      },
      method: 'POST'
    }, '', res => {
      _that.setData({
        timal: res.data.data,
        timal_msg: ''

      })
    }, res => {
      if (res.data.error_code == 400 && res.data.msg == 'token无效或已过期') {
        app.refreshtoken(token);
        setTimeout(() => {
          _that.addpage();
        }, 1500)
      } else if (res.data.error_code == 400) {
        _that.setData({
          timal_msg: res.data.msg
        })
        // $Toast({
        //   content: res.data.msg,
        //   type: 'warning'
        // });
      }
    });
  },



  saom() {
    let _that = this;
    var token = wx.getStorageSync('token');
    if (!token) {
      return;
    }
    let net = new NetWork(_that.data._baseUrl)
    net._request({
      url: 'api/v1/menu/get_orderData',
      data: {
        //需要获取店铺id，所以要去获取，因为我们要去获取上一页的店铺id所以要去onLoad里面获取
        token: token,
        device_id: _that.data.device_id
      },
      method: 'POST'
    }, '', res => {
      var data = res.data.data;
      _that.setData({
        id: data.store.id,
        store_name: data.store.store_name,
        address: data.store.province + data.store.city + data.store.district + data.store.address,
        'usreAdd.address': data.store.address,
        'usreAdd.city': data.store.city,
        'usreAdd.province': data.store.province,
        'usreAdd.district': data.store.district,
        "usreAdd.latitude": data.store.lat,
        "usreAdd.longitude": data.store.lng
      })
    }, res => {
      if (res.data.error_code == 400 && res.data.msg == 'token无效或已过期') {
        app.refreshtoken(token);
        setTimeout(() => {
          _that.addpage();
        }, 1500)
      }

    });
  },



  /* 拨打电话 */
  telPhone() {
    var that = this;
    wx.makePhoneCall({
      phoneNumber: ''
    }, res => {

    });
  },

  myvehicle() {
    wx.navigateTo({
      url: './myvehicle',
    })
  },

  onReady: function(e) {

  },

  //three、添加订单，提交订单
  formSubmit(e) {
    var _that = this;

    var isclick = _that.data.isclick;

    if(isclick){
      return;
    }

    _that.setData({
      isclick:1
    })

    setTimeout(() => {
      _that.setData({
        isclick: 0
      })
    }, 2000)

    var { value } = e.detail;
    // console.log(value,"value")
    // return;

    // 正在执行中的代码
    $Toast({
      content: "提交中",
      type: 'loading'
    });

    // if (!value) {
    //   value = _that.data.dates;
    // }


    let reg_tpl = /^1[3456789]\d{9}$/
    for (let i in value) {
      let values = value[i];
      if (!values) {
        $Toast({
          content: '内容不能为空',
          type: 'none'
        })
        return;
      }
      if (i == 'phone' && !reg_tpl.test(values)) {
        $Toast({
          content: '手机号码不正确!',
          type: 'none'
        })
        return;
      }

    }

    var {
      dail,
      cid,
      timal,
      id,
      usreAdd,
      timal_msg,
      dage,
      _baseUrl,
      deviceList,
      indext
    } = _that.data;
    //menuInfo接口后台返回的提示语，在munuInfo接口处设置
    if (timal_msg) {
      $Toast({
        content: timal_msg,
        type: 'warning'
      
      });
    }
    // 延迟
    setTimeout(() => {
      let url = '';
      if (_that.data.dage == 2){
        url = 'api/v1/order/addStoreOrder'
      }
      else{
        url = 'api/v1/order/addOrder'
      }      
      value.token = wx.getStorageSync('token');
      value.remark = dail; 
      value.device_id = deviceList.o[indext].id;
      var net = new NetWork(_baseUrl);
      net._request({
        //点触发那个位置的时候传输数据就在那个位置写
        url: url,
        method: 'POST',
        data: value
      }, '提交订单', res => {

        // 跳转下一页/传参，传参不在接口传，在这里传
      
        setTimeout(() => {

          if (_that.data.dage == 1) {
            wx.redirectTo({
              url: './orderdetails?id= ' + res.data.data.order_id
            })
          }

          if (_that.data.dage == 2) {
            // wx.redirectTo({
            //   url: '../inservice/inservice'
            // })
            wx.navigateTo({
              url: '../personal/inservice/inservice?id= ' + res.data.data.order_id
            })
          }

          // 跳去下一页的时候清除设备ID的缓存，不然它还会读取扫码的柜子地址
          // 这样正常程序进入的时候它还有获取到柜子地址
          // 注：扫码进去的地址是柜子当前的地址 而正常进去的地址是首页也就是当前位置（统称当前位置）
          wx.removeStorageSync("scene")
        }, 1500)

      }, res => {
        var data = res.data;
        if (data.error_code == 400 && data.msg == 'token无效或已过期') {
          //token过期 重新执行该函数
          app.refreshtoken(token);
          setTimeout(() => {
            $Toast({
              content: "提交失败，请重新提交",
              type: 'warning'
            })

          }, 1500)
        } else if (data.error_code == 400) {
          $Toast({
            content: data.msg,
            type: 'warning'
          });
        }

      });
    }, 1000)
  },



  playt() {
    var _that = this;
    var {
      timal_msg
    } = _that.data;
    $Toast({
      content: timal_msg,
      type: 'warning'
    });
  },
  
  again(e){
    var _that = this;
    console.log(e,"ee")
    _that.setData({
      dage: e.currentTarget.dataset.id
    })
    
  },
  /* 修改头部标题 */
  setTitle(str) {
    wx.setNavigationBarTitle({
      title: str,
      success: function() {

      }
    })
  },
  onShareAppMessage(str) {
    return {
      title: str,
      path: this.route
    }
  },


  /* 隐藏分享功能 */
  hideShare() {
    wx.hideShareMenu()
  },
  /* 分享功能 */
  showShare() {
    wx.showShareMenu()
  },
  /* 下拉刷新触发功能 */
  onPullDownRefresh() {
    // 下拉刷新事件
    // wx.startPullDownRefresh
    // wx.stopPullDownRefresh
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)

  },

  /* 开启上拉到底部触发功能 */
  startDonwEven() {
    wx.startPullDownRefresh()
  },
  /* 停止上拉到底部触发功能 */
  stopDownEven() {
    wx.stopPullDownRefresh()
  },
  onReachBottom() {
    // 上拉触底事件
    //console.log('触发触底事件')
  },

  onPageScroll(res) {
    // 页面滚动事件
    //console.log(res.scrollTop)
  },





  isUserInfo() {
    var _that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          _that.setData({
            auth: false
          })
        } else {
          _that.setData({
            auth: true
          })
        }
      }
    })
  },

  userInfo(e) {
    let _userInfo = e.detail.userInfo;
    let net = new NetWork(app.globalData._baseUrl);
    var _that = this;

    if (_userInfo) {
      this.setData({
        auth: true
      })
    }
    var {
      signature,
      rawData,
      iv,
      encryptedData
    } = e.detail;


    wx.login({
      success(res) {
        // console.log('小程序登录信息', res)
        if (res.code) {
          net._request({
            url: 'api/v1/member/wxlogin',
            method: 'POST',
            data: {
              code: res.code,
              signature: signature,
              rawData: rawData,
              iv: iv,
              encryptedData: encryptedData
            },
          }, false, sres => {
            if (sres.data.error_code == 0) {

              var _data = sres.data.data;


              // var _data = sres.data.data;
              wx.setStorageSync("user", _data.user)

              wx.setStorageSync("token", _data.access_token)

              _that.setData({
                user: _data.user,
              })
              _that.saom()
              _that.vehicleList()

              // _that.setData({
              //   token: _data.access_token
              // })

            }
          });
        }
      }
    })


  }


})